package sgi.client;

import java.io.IOException;
import java.util.Iterator;

import sgi.details_new.MessageDetails;
import sgi.message.MessageViewMessages;

public class SGIMessagesController extends SGIController {

	public static SGIMessagesController messages;
	public static SGIMessagesUI messagesUI;
	/** constructor */
	public SGIMessagesController() {
		SGIMessagesController.messagesUI = new SGIMessagesUI();
	}
	
	/** create controller */
	public static SGIMessagesController create() throws IOException
	{
		if(SGIMessagesController.messages == null)
		{
			SGIMessagesController.messages = new SGIMessagesController();
			messagesUI.setMessagesController(SGIMessagesController.messages);
		}
		SGIMessagesController.messagesUI.setVisible(true);
		return messages;
	}
	/** terminate UI */
	public static void terminate()
	{
		SGIMessagesController.messagesUI.setVisible(false);
		SGIMessagesController.messages=null;
		SGIMessagesController.messagesUI.setVisible(false);
		SGIMessagesController.messagesUI=null;
	}
	
	/** getUI  */
	public static SGIMessagesUI getUI()
	{
		return messagesUI;
	}

	/** sending message of review messages */
	public void ReviewMessages() {
		MessageViewMessages msg = new MessageViewMessages(SGIUserAccountMenuController.getUser().getUsername());
		sendViewMessages(msg);
		
	}

	
	private void sendViewMessages(MessageViewMessages msg) {
		try {
			(SGIClientConnectionController.createConnection()).handleMessageFromClientUI(msg);
		} catch  (IOException e) {e.printStackTrace();}
		
	}
	/** handle message showing messages in message table */
	@Override
	void handleMessage(Object msg) {
		Iterator<MessageDetails> iterator = (((MessageViewMessages)msg).getMessages()).iterator();
		SGIMessagesController.messagesUI.clearTable();
		while (iterator.hasNext()) {
			SGIMessagesController.messagesUI.addRows(iterator.next());
		}

	}

}
